<?php
namespace app\common\library;

use Gregwar\Captcha\CaptchaBuilder;

class Captcha{
    protected static self $instanse;
    protected static string $seed;
    protected int $length;
    protected int $expire;

    public function __construct($config = [])
    {
        if(!$config) {
            $config = config('captcha');
        }
        self::$seed = $config['codeSet'];
        $this->length = $config['length'];
        $this->expire = $config['expire'];
    }

    public static function getInstanse(){
        if (!self::$instanse) {
            self::$instanse = new self();
        }
        return self::$instanse;
    }

    public static function create($key='', $length = 5)
    {
        $captcha = new CaptchaBuilder();
        $captcha->build();
        $phraseBuilder = $captcha->getPhrase();
        if(!$key){
            $key = md5(uniqid());
        }
        cache('captcha_'.$key, $phraseBuilder, 120);
        return ['base64'=>$captcha->inline(), 'key' => $key];
    }

    public static function check($code, $key, $strict = false)
    {
        $phraseBuilder = cache('captcha_'.$key);
        if(!$phraseBuilder){
            return false;
        }
        if($strict){
            return $phraseBuilder === $code;
        }
        return strtoupper($phraseBuilder) == strtoupper($code);
    }
}